<template>
  <view @click="hide" style="height: 100%">
    <scroll-view
    class="scroll-view"
      scroll-y="true"
      :class="isShow?'contentplus':'content' "
      :scroll-into-view="scrollInto"
      scroll-with-animation
    >
      <!-- 消息列表 -->
      <block v-for="(item, index) in chatList" :key="index">
        <view :id="'chat' + index">
          <user-chat-card
         :message="item"
         :userId="userId"
          />
        </view>
      </block>
    </scroll-view>
    <!-- 底部栏 -->
    <view class="footer-btn">
      <user-chat-bottom
        @submit="submit"
        @focusInput="focusInput"
        :showB="isShow"
        ref="kid"
        @ad="adds()"
        @mi="minus()"
        @down="goDown()"
        @func="getData"
		    :clearData="clearData"
      />
    </view>
  </view>
</template>

<script>
import userChatCard from "./childComps/userChatCard";
import userChatBottom from "./childComps/userChatBottom.vue";

export default {
  components: {
    userChatCard,
    userChatBottom,
  },
  data() {
    return {
      clearData: false,
      userId: '', // 固定当前用户ID
      user: {},
      scrollInto: "",
      scrollH: 0,
      chatList: [], // 聊天记录
      isShow: false,
      timer: null,
      pollingTimer: null, // 轮询定时器
      ws: null, // WebSocket实例
      //目标用户ID
      targetUserId: '',
    };
  },

  onLoad(option) {
    // 获取当前用户ID，确保是字符串类型
    this.userId = String(uni.getStorageSync('uid'));

    // 获取目标用户ID
    if (option.targetUserId) {
      // 从联系人列表跳转，直接获取目标用户ID
      this.user = {
        _id: String(option.targetUserId),  // 确保目标用户ID也是字符串
        nickname: option.targetUserName || '用户'
      };
    } else if (option.user) {
      // 从消息列表跳转，解析JSON获取用户信息
      try {
        const userData = JSON.parse(decodeURIComponent(option.user));
        this.targetUserId = String(userData._id);
        //打印
        console.log('目标用户ID:', this.targetUserId);
        this.user = {
          _id: String(userData._id),  // 确保目标用户ID是字符串
          nickname: userData.nickname || '用户'
        };
      } catch (e) {
        console.log('解析用户参数失败');
        this.user = {
          _id: 'user_002',
          nickname: '用户'
        };
      }
    } else {
      // 默认用户
      this.user = {
        _id: 'user_002',
        nickname: '用户'
      };
    }

    // 设置页面标题
    uni.setNavigationBarTitle({
      title: this.user.nickname,
    });

    // 获取聊天记录
    this.getChatList();
    
    // 启动实时通信
    this.startRealTimeCommunication();
    
    // 启动定时轮询作为备用方案
    this.startPolling();
  },

  onReady() {
    // 页面就绪后滚动到底部
    this.$nextTick(() => {
      this.goDown();
    });
  },

  onUnload(){
     clearInterval(this.timer);
     clearInterval(this.pollingTimer);
     this.stopRealTimeCommunication();
  },

  watch: {
    chatList(newVal) {
      if (newVal) {
        this.goDown();
      }
    },
  },

  methods: {
    // 启动实时通信
    startRealTimeCommunication() {
      console.log('启动实时通信...');
      this.connectWebSocket();
    },
    
    // 停止实时通信
    stopRealTimeCommunication() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
        console.log('WebSocket连接已关闭');
      }
    },
    
    // 启动定时轮询
    startPolling() {
      // 清除之前的定时器
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
      }
      
      // 每5秒轮询一次新消息
      this.pollingTimer = setInterval(() => {
        this.pollForNewMessages();
      }, 10000);
      
      console.log('定时轮询已启动');
    },
    
    // 轮询获取新消息
    pollForNewMessages() {
      console.log('轮询检查新消息...');
      const data = {
        userId: this.userId,
        targetUserId: this.targetUserId,
        lastMessageTime: this.getLastMessageTime() // 获取最后一条消息的时间
      };
      
      // 检查getNewMessages接口是否存在，如果不存在则使用getChatData接口
      if (this.$api.chat.getNewMessages) {
        this.$api.chat.getNewMessages(data).then((res) => {
          if (res.code === 200 && res.data && res.data.length > 0) {
            console.log('发现新消息:', res.data.length, '条');
            this.addNewMessages(res.data);
          }
        }).catch((err) => {
          console.error('轮询获取新消息失败:', err);
          // 如果getNewMessages接口不存在，回退到getChatData
          this.fallbackPolling();
        });
      } else {
        this.fallbackPolling();
      }
    },
    
    // 备用轮询方法
    fallbackPolling() {
      const data = {
        userId: this.userId,
        targetUserId: this.targetUserId
      };
      
      this.$api.chat.getChatData(data).then((res) => {
        if (res.code === 200 && res.data) {
          // 比较新旧消息，只添加新消息
          this.compareAndAddNewMessages(res.data);
        }
      }).catch((err) => {
        console.error('备用轮询失败:', err);
      });
    },
    
    // 比较并添加新消息
    compareAndAddNewMessages(newMessages) {
      if (!this.chatList || this.chatList.length === 0) {
        this.chatList = newMessages;
        return;
      }
      
      // 获取当前最后一条消息的ID
      const lastMessageId = this.chatList[this.chatList.length - 1].id;
      
      // 找到新消息的起始位置
      let startIndex = newMessages.findIndex(msg => msg.id === lastMessageId);
      
      if (startIndex === -1) {
        // 如果没有找到相同的消息ID，可能是全新的消息列表
        this.chatList = newMessages;
      } else {
        // 添加从startIndex+1开始的新消息
        const newMessagesToAdd = newMessages.slice(startIndex + 1);
        if (newMessagesToAdd.length > 0) {
          console.log('发现新消息:', newMessagesToAdd.length, '条');
          this.addNewMessages(newMessagesToAdd);
        }
      }
    },
    
    // 获取最后一条消息的时间
    getLastMessageTime() {
      if (this.chatList && this.chatList.length > 0) {
        const lastMessage = this.chatList[this.chatList.length - 1];
        return lastMessage.create_time;
      }
      return 0;
    },
    
    // 添加新消息到聊天列表
    addNewMessages(messages) {
      messages.forEach(message => {
        // 检查是否重复消息
        if (this.isDuplicateMessage(message.id)) {
          return;
        }
        
        const newMsg = {
          id: message.id,
          from_id: message.from_id,
          from_name: message.from_name,
          from_avatar: message.from_avatar,
          content: message.content,
          create_time: message.create_time,
          chat_time: this.showTime(message.create_time),
          isSelf: message.from_id === this.userId
        };
        
        this.chatList.push(newMsg);
      });
      
      // 如果有新消息，滚动到底部
      if (messages.length > 0) {
        this.goDown();
      }
    },
    
    // 连接WebSocket
    connectWebSocket() {
      try {
        // WebSocket服务器地址（需要根据实际后端配置修改）
        const wsUrl = 'ws://localhost:9100/ws/chat';
        
        console.log('连接WebSocket进行实时通信:', wsUrl);
        
        this.ws = uni.connectSocket({
          url: wsUrl,
          header: {
            'userId': this.userId,
            'targetId': this.targetUserId
          }
        });
        
        // 监听WebSocket打开事件
        this.ws.onOpen(() => {
          console.log('WebSocket连接成功，开始实时接收消息');
        });
        
        // 监听WebSocket消息事件（接收实时消息）
        this.ws.onMessage((res) => {
          console.log('接收到实时消息:', res.data);
          this.handleRealTimeMessage(res.data);
        });
        
        // 监听WebSocket关闭事件
        this.ws.onClose(() => {
          console.log('WebSocket连接关闭，尝试重新连接...');
          // 3秒后尝试重新连接
          setTimeout(() => {
            this.connectWebSocket();
          }, 3000);
        });
        
        // 监听WebSocket错误事件
        this.ws.onError((err) => {
          console.error('WebSocket错误:', err);
        });
        
      } catch (error) {
        console.error('创建WebSocket连接异常:', error);
      }
    },
    
    // 处理实时接收到的消息
    handleRealTimeMessage(messageData) {
      try {
        const message = JSON.parse(messageData);
        
        // 只处理聊天消息类型
        if (message.type === 'chat') {
          this.addRealTimeMessage(message);
        }
      } catch (error) {
        console.error('解析实时消息失败:', error);
      }
    },
    
    // 添加实时接收到的消息
    addRealTimeMessage(message) {
      // 检查是否重复消息
      if (this.isDuplicateMessage(message.msgId)) {
        console.log('忽略重复消息:', message.msgId);
        return;
      }
      
      const newMsg = {
        id: message.msgId || 'msg_' + Date.now(),
        from_id: message.senderId,
        from_name: message.senderName || this.user.nickname,
        from_avatar: message.senderAvatar || this.user.avatar,
        content: message.content,
        create_time: message.sendTime ? new Date(message.sendTime).getTime() : Date.now(),
        chat_time: this.showTime(Date.now()),
        isSelf: message.senderId === this.userId // 判断是否是自己发送的消息
      };
      
      // 添加到聊天列表
      this.chatList.push(newMsg);
      this.goDown();
      
      console.log('实时消息已添加到聊天列表');
    },
    
    // 新增：检查重复消息
    isDuplicateMessage(msgId) {
      return this.chatList.some(msg => msg.id === msgId);
    },
    
    // 删除：初始化模拟聊天数据（函数不存在）
    initMockChatData() {
      // 模拟聊天记录
      this.chatList = [
        {
          id: 'msg_001',
          from_id: this.user._id,
          from_name: this.user.nickname,
          from_avatar: this.user.avatar,
          content: '你好！这是一条测试消息',
          create_time: new Date().getTime() - 300000, // 5分钟前
          chat_time: this.showTime(new Date().getTime() - 300000),
          isSelf: false
        },
      ];

      this.goDown();
    },

    // 获取聊天记录
    getChatList() {
      console.log('获取聊天记录...');
      console.log('用户ID:', this.userId);
      console.log('目标用户ID:', this.targetUserId);
      const data = {
        userId: this.userId,
        targetUserId: this.targetUserId,
      };
      this.$api.chat.getChatData(data).then((res) => {
        if (res.code === 200) {
          this.chatList = res.data;
          console.log('聊天记录获取成功，共', res.data.length, '条消息');
          
          // 获取成功后滚动到底部
          this.$nextTick(() => {
            this.goDown();
          });
        } else {
          console.error('获取聊天记录失败:', res.message);
          // 如果API失败，使用模拟数据
          this.initMockChatData();
        }
      })
      .catch((err) => {
        console.error('获取聊天记录请求失败:', err);
        // 如果请求失败，使用模拟数据
        this.initMockChatData();
      });
    },

    showTime(time) {
      const date = new Date(time);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    //发送消息（向后端发送）
    submit(content) {
      if (!content.trim()) {
        return;
      }
      
      // 生成消息ID
      const msgId = this.generateMsgId();
      const sendTime = this.formatDateTime(new Date());
      
      // 创建消息对象，符合后端要求的格式
      const messageData = {
        msgId: msgId,
        senderId: this.userId, // 当前用户ID
        targetId: this.user._id, // 目标用户ID
        content: content,
        sendTime: sendTime
      };
      
      // 先在前端显示消息
      const newMsg = {
        id: msgId,
        from_id: this.userId,
        from_name: '我',
        from_avatar: '/static/logo.png',
        content: content,
        create_time: new Date().getTime(),
        chat_time: this.showTime(new Date().getTime()),
        isSelf: true
      };
      
      this.chatList.push(newMsg);
      this.clearData = true;
      this.goDown();
      
      // 向后端发送消息
      this.sendMessageToBackend(messageData);
    },
    
    // 生成消息ID
    generateMsgId() {
      return 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    },
    
    // 格式化时间为后端要求的格式
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 向后端发送消息
    sendMessageToBackend(messageData) {
      // 这里调用后端API发送消息
      this.$api.chat.sendMessage(messageData).then((res) => {
        if (res.code === 200) {
          console.log('消息发送成功:', res.data);
          // 消息发送成功，可以更新消息状态（如已送达、已读等）
        } else {
          console.error('消息发送失败:', res.message);
          // 可以在这里添加失败处理逻辑，比如显示发送失败提示
          uni.showToast({
            icon: 'none',
            title: '消息发送失败',
            duration: 2000
          });
        }
      }).catch((err) => {
        console.error('发送消息请求失败:', err);
        uni.showToast({
          icon: 'none',
          title: '网络错误，请重试',
          duration: 2000
        });
      });
    },
    
    //获取焦点时
    focusInput() {
      this.goDown();
    },
    
    //滚动到底部
    goDown() {
      if(!this.chatList) return;
      let lastIndex = this.chatList.length - 1;

      if (lastIndex < 0) return;
      this.scrollInto = "";
      this.$nextTick(() => {
        this.scrollInto = "chat" + lastIndex;
      });
    },
    
    hide() {
      if (this.isShow) {
        this.$refs.kid.showBottom();
        this.isShow = false;
      }
    },
    
    getData(data) {
      if (data) {
        this.isShow = data;
      }
    },
    
    minus() {
      this.scrollH = this.scrollH - uni.upx2px(354);
      this.goDown();
    },
    
    adds() {
      this.scrollH = this.scrollH + uni.upx2px(354);
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f6f7;
  height: 100%;
}

.content {
  padding: 0;
  position: fixed;
  left: 0;
  /* #ifdef H5 */
  top: 80rpx;
  height: calc(100vh - 180rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  top: 0rpx;
  height: calc(100vh - 100rpx);
  /* #endif */
  width: 750rpx;
}
  /* #ifdef MP-WEIXIN */
  .scroll-view{
    height: calc(100vh - 100rpx);
  }
  /* #endif */
.contentplus {
  padding: 0;
  position: fixed;
  left: 0;
  /* #ifdef H5 */
  top: 80rpx;
  height: calc(100vh - 520rpx);
  /* #endif */
  /* #ifdef APP-PLUS */
  top: 0rpx;
  height: calc(100vh - 440rpx);
  /* #endif */
  width: 750rpx;
}
.footer-btn {
	background-color: #f5f6f7;
  width: 750rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  // height: 100rpx;
}
</style>